package com.acane.instagram.feature.post

import android.content.Context
import android.graphics.Bitmap
import android.media.MediaMetadataRetriever
import android.media.MediaPlayer
import android.net.Uri
import android.util.Log
import android.view.ViewGroup
import android.widget.MediaController
import android.widget.VideoView
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

// 独立缩略图生成函数
suspend fun generateVideoThumbnail(
    context: Context,
    videoUri: String,
    timeMicroSec: Long = 0
): ImageBitmap? = withContext(Dispatchers.IO) {
    val retriever = MediaMetadataRetriever()
    try {
        val uri = Uri.parse(videoUri)
        return@withContext context.contentResolver.openFileDescriptor(uri, "r")?.use { pfd ->
            retriever.setDataSource(pfd.fileDescriptor)
            getFrame(retriever, timeMicroSec)
        } ?: run {
            // 备用方案（适配不同Android版本）
            retriever.setDataSource(context, uri)
            getFrame(retriever, timeMicroSec)
        }
    } catch (e: Exception) {
        null
    } finally {
        retriever.release()
    }
}

 fun getFrame(retriever: MediaMetadataRetriever, timeMicroSec: Long): ImageBitmap? {
    return retriever.getFrameAtTime(timeMicroSec)?.let { bitmap ->
        // 优化缩略图尺寸
        Bitmap.createScaledBitmap(
            bitmap,
            bitmap.width / 4,  // 缩小尺寸提升性能
            bitmap.height / 4,
            true
        ).asImageBitmap()
    }
}
@Composable
fun UploadVideoPlayerWithThumbnail(videoUrl: String, viewModel: PostViewModel) {
    val context = LocalContext.current
    var playbackError by remember { mutableStateOf<String?>(null) }
    var showFullScreen by remember { mutableStateOf(false) }
    var thumbnailBitmap by remember { mutableStateOf<ImageBitmap?>(null) }
    val coroutineScope = rememberCoroutineScope()



    // 生成缩略图
    LaunchedEffect(Unit) {
        coroutineScope.launch(Dispatchers.IO) {
            thumbnailBitmap = generateVideoThumbnail(context, videoUrl).also {
                if (it == null) {
                    playbackError = "无法生成视频缩略图"
                    Log.e("VideoPlayer", "缩略图生成失败: $videoUrl")
                }
            }
            Log.d("VideoPlayer", "缩略图生成成功，准备将缩略图存入数据库: $videoUrl")
            //viewModel.thumbnailUrl = thumbnailBitmap.toString()
            Log.d("VideoPlayer", "缩略图已存入数据库: $videoUrl")
        }
    }
        // 显示缩略图
        thumbnailBitmap?.let { bitmap ->
            Image(
                bitmap = bitmap,
                contentDescription = "视频缩略图",
                modifier = Modifier
                    //.padding(8.dp)
                    .size(350.dp)
                    .clickable { showFullScreen = true }
                    .clip(RoundedCornerShape(8.dp)),
                contentScale = ContentScale.Crop,
            )
        }

        // 全屏播放对话框
        if (showFullScreen) {
            Dialog(
                onDismissRequest = { showFullScreen = false },
                properties = DialogProperties(
                    usePlatformDefaultWidth = false,
                    decorFitsSystemWindows = false
                )
            ) {
                FullScreenVideoPlayer(
                    videoUrl = videoUrl,
                    onDismiss = { showFullScreen = false },
                    onError = { error -> playbackError = error }
                )
            }
        }

        // 错误提示
        playbackError?.let { message ->
            Text(
                text = message,
                color = MaterialTheme.colorScheme.error,
                modifier = Modifier.padding(8.dp)
            )
        }
    //}
}

@Composable
private fun FullScreenVideoPlayer(
    videoUrl: String,
    onDismiss: () -> Unit,
    onError: (String) -> Unit
) {
    val context = LocalContext.current

    AndroidView(
        factory = { androidContext ->
            VideoView(androidContext).apply {
                layoutParams = ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
                )

                setVideoURI(Uri.parse(videoUrl))
                setOnPreparedListener { mediaPlayer ->
                    // 设置循环播放
                    mediaPlayer.isLooping = true
                    // 居中显示视频
                    mediaPlayer.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING)
                    start()
                }
                setMediaController(MediaController(context))
                setOnErrorListener { _, what, extra ->
                    onError("播放失败: 代码 $what, 附加信息 $extra")
                    false
                }
            }
        },
        modifier = Modifier
            .fillMaxSize()
            .clickable { onDismiss() }
    )
}